import { PenEventProps } from "@/types";
import { FormRowCol } from "@/components/common/FormRowCol.tsx";
import { Button, Divider, Drawer, Input, InputRef, Select, Space } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons";
import { deepClone } from "@meta2d/core";
import { EventSetTarget } from "@/components/Configuration/PenProps/components/EventSetTarget.tsx";
function SetProps({
  item,
  index,
  onRemove,
  onChange,
}: {
  item: { key: string; value: string };
  index: number;
  onRemove: (index: number) => void;
  onChange: (key: "key" | "value", value: string, index: number) => void;
}) {
  const [items, setItems] = useState([
    "background",
    "color",
    "text",
    "width",
    "height",
    "visible",
    "progress",
    "value",
  ]);
  const [name, setName] = useState("");
  const inputRef = useRef<InputRef>(null);

  const onNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };

  const addItem = (
    e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>,
  ) => {
    e.preventDefault();
    if (name.trim() == "") {
      return false;
    }
    setItems([...items, name]);
    localStorage.setItem("setPropsKeys", JSON.stringify([...items, name]));
    setName("");
    setTimeout(() => {
      inputRef.current?.focus();
    }, 0);
  };
  useEffect(() => {
    let storageList = localStorage.getItem("setPropsKeys");
    if (storageList != null) {
      setItems(() => JSON.parse(storageList || "[]"));
    }
  }, []);
  return (
    <>
      <Space style={{ margin: "5px 0" }}>
        <Select
          placeholder="key"
          style={{ width: 170 }}
          value={item.key}
          onSelect={(value) => {
            onChange("key", value, index);
          }}
          dropdownRender={(menu) => (
            <>
              {menu}
              <Divider style={{ margin: "8px 0" }} />
              <Space style={{ padding: "0 8px 4px" }}>
                <Input
                  placeholder="自定义属性"
                  ref={inputRef}
                  value={name}
                  onChange={onNameChange}
                  onKeyDown={(e) => e.stopPropagation()}
                />
                <Button
                  icon={<PlusOutlined />}
                  type="primary"
                  size={"small"}
                  onClick={addItem}
                ></Button>
              </Space>
            </>
          )}
          options={items.map((item) => ({ label: item, value: item }))}
        />
        <Input
          placeholder="value"
          value={item.value}
          onChange={(e) => {
            onChange("value", e.target.value, index);
          }}
        />
        <Button
          onClick={() => onRemove(index)}
          icon={<DeleteOutlined />}
        ></Button>
      </Space>
    </>
  );
}
export function EventSetProps(props: PenEventProps) {
  const [openProps, setOpenProps] = useState(false);
  const [list, setList] = useState<{ key: string; value: string }[]>([]);
  useEffect(() => {
    let newList: { key: string; value: string }[] = [];
    if (typeof props.item.value == "object" && props.item.value != null) {
      for (let key in props.item.value) {
        newList.push({
          key,
          value: props.item.value[key],
        });
      }
      setList(() => newList);
    }
  }, []);

  const handleAddItem = () => {
    setList((v) => {
      return [
        ...v,
        {
          key: "background",
          value: "",
        },
      ];
    });
  };
  const handleRemoveItem = (index: number) => {
    let newList = deepClone(list);
    newList.splice(index, 1);
    setList(() => newList);
  };
  const handleChangeItem = (
    key: "key" | "value",
    value: string,
    index: number,
  ) => {
    let newList = deepClone(list);
    newList[index][key] = value;
    setList(() => newList);
  };
  const setParam = () => {
    setOpenProps(false);
    let newList = deepClone(list);
    let value: { [key: string]: any } = {};
    for (let i = 0; i < newList.length; i++) {
      let item = newList[i];
      value[item.key] = item.value;
    }

    props.onChange("value", value, props.index);
  };
  return (
    <>
      <Space style={{ padding: "0" }} className={"w-full"} direction="vertical">
        <EventSetTarget {...props} />
        <FormRowCol label="配置属性">
          <Drawer
            title="配置属性"
            placement="right"
            onClose={() => setOpenProps(false)}
            open={openProps}
            extra={
              <Space>
                <Button type="primary" size={"small"} onClick={handleAddItem}>
                  添加
                </Button>
                <Button type="primary" size={"small"} onClick={setParam}>
                  确定
                </Button>
              </Space>
            }
          >
            {list.map((item, index) => (
              <SetProps
                index={index}
                item={item}
                onRemove={handleRemoveItem}
                onChange={handleChangeItem}
                key={`SetProps${index}`}
              />
            ))}
          </Drawer>
          <Button onClick={() => setOpenProps(true)}>配 置</Button>
        </FormRowCol>
      </Space>
    </>
  );
}
